package com.highspeed.bdk.service.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created by chenjiabin on 2018/3/23.
 */
public abstract class BdkBaseService<T, ID extends Serializable> implements IBdkBaseService<T, ID> {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public <S extends T> S save(S entity) {
        return getRepository().save(entity);
    }

    @Override
    public <S extends T> S saveAndFlush(S entity) {
        return getRepository().saveAndFlush(entity);
    }


    @Override
    public <S extends T> List<S> save(Iterable<S> entities) {
        return getRepository().saveAll(entities);
    }


    @Override
    public void delete(ID id) {
        getRepository().deleteById(id);
    }

    @Override
    public void delete(ID[] ids) {
        if (ids != null) {
            for (ID id : ids) {
                getRepository().deleteById(id);
            }
        }
    }


    @Override
    public T getOne(ID id) {
        return getRepository().getOne(id);
    }

    @Override
    public T findOne(ID id) {
        Optional<T> optional = getRepository().findById(id);
        if (optional != Optional.empty()) {
            return optional.get();
        }
        return null;
    }


    public List<T> all() {
        return getRepository().findAll();
    }


    @Override
    public Page<T> query(Map<String, Object> params, Pageable pageable) {
        return getRepository().findAll(params, pageable);
    }

    @Override
    public Page<T> queryDistinct(Map<String, Object> params, Pageable pageable) {
        return getRepository().findAllDistinct(params, pageable);
    }

    @Override
    public List<T> queryToList(Map<String, Object> params, Pageable pageable) {
        return getRepository().findAll(params, pageable).getContent();
    }

    @Override
    public List<T> queryDistinctToList(Map<String, Object> params, Pageable pageable) {
        return getRepository().findAllDistinct(params, pageable).getContent();
    }


    @Override
    public boolean exists(ID id) {
        return getRepository().existsById(id);
    }

    @Override
    public <S extends T> boolean exists(Example<S> example) {
        return getRepository().exists(example);
    }


    @Override
    public long count() {
        return getRepository().count();
    }

    @Override
    public <S extends T> long count(Example<S> example) {
        return getRepository().count(example);
    }


    @Override
    public void flush() {
        getRepository().flush();
    }

    @Override
    public void clear() {
        getRepository().clear();
    }
}
